<template>
  <div class="redirect-contianer"><a-spin /></div>
</template>

<script lang="ts">
  import { defineComponent, nextTick } from 'vue'
  import { mapState } from 'pinia'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import useCachedRouteStore from '@/store/modules/cached-routes'

  export default defineComponent({
    name: 'RedirectComponent',
    computed: {
      ...mapState(useVisitedRouteStore, ['getVisitedRoutes']),
      ...mapState(useCachedRouteStore, ['cachedRoutes']),
    },
    created() {
      this.reload()
    },
    methods: {
      reload() {
        const { query, path, fullPath } = this.$route
        const origin_path = path.slice(9)
        const origin_fullPath = fullPath.slice(9)
        // 1.判断已经打开的visited-routers中是否存在
        const route = this.getVisitedRoutes.find((it) => {
          let fullPathEqual = it.fullPath === origin_fullPath
          let pathEqual = it.path === origin_path
          // let queryEqual = JSON.stringify(it.query) === JSON.stringify(query)
          // return fullPathEqual || (pathEqual && queryEqual)
          return fullPathEqual || pathEqual
        })
        // 2.没有直接跳转
        if (!route) {
          this.$router.replace({
            path: origin_fullPath,
            query,
          })
          return
        }
        // 3. visited-routers移除要去的route（解决keep-alive）
        const pageName = route.name
        const delIndex = this.cachedRoutes.findIndex((it) => it == pageName)
        // 是否已缓存
        if (delIndex !== -1) {
          this.cachedRoutes.splice(delIndex, 1)
        }
        // 4.跳转路由
        this.$router.replace({
          path: origin_fullPath,
          query,
        })
        // 5.缓存路由
        if (route.meta.cacheable !== false) {
          nextTick(() => {
            this.cachedRoutes.push(pageName)
          })
        }
      },
    },
  })
</script>
